package com.example.jimuyutabletcontrol.utils;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.example.jimuyutabletcontrol.R;
import com.example.jimuyutabletcontrol.bean.MeasuringDistanceLine;
import com.example.jimuyutabletcontrol.bean.MeasuringDistancePoint;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: HDX
 * @date: 2020\5\11 0011
 */
public class MeasuringDistancePointHelp {

    public static final String KEY_POINT = "key_params"+MeasuringDistancePointHelp.class;

    public static final String START_POINT = "start_point";

    public static final String END_POINT = "end_point";

    private final String[] measureDistanceTexts = {
            "1", "2"
    };

    private Activity activity;

    private BaiduMap baiduMap;

    private View measuringDistancePoint;

    private MeasuringDistanceLine measuringDistanceLine;

    private List<MeasuringDistancePoint> measuringDistancePoints;

    private BaiduMap.OnMapClickListener mapClickListener;

    private OnMeasuringDistanceListener listener;

    private int priority;

    public MeasuringDistancePointHelp(Activity activity, BaiduMap baiduMap,int priority) {
        this.activity = activity;
        this.baiduMap = baiduMap;
        this.priority = priority;
        initData();
        setListeners();
    }

    public void setOnMeasuringDistanceListener(OnMeasuringDistanceListener listener) {
        this.listener = listener;
    }

    public interface OnMeasuringDistanceListener {
        void onMeasuringDistanceListener(boolean isALLShow,int distance);
    }

    private void setListeners() {
        baiduMap.setOnMapClickListener(mapClickListener = new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                addMeasuringDistancePoint(latLng);
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {

            }
        });
    }

    private void addMeasuringDistancePoint(LatLng latLng) {
        if (isHasMeasuringDistancePoint(0)) {
            if (isHasMeasuringDistancePoint(1)) {
                clearMeasuringDistancePoint();
            } else {
                measurePoint(latLng, 1);
                createMeasurLine();
            }
        } else {
            measurePoint(latLng, 0);
        }
    }

    private void measurePoint(LatLng latLng, int i) {
        MeasuringDistancePoint measurePoint = measuringDistancePoints.get(i);
        if (null != measurePoint) {
            if (null == measurePoint.overlay || measurePoint.overlay.isRemoved()) {
                measurePoint.selfPosition = latLng;
                if (measurePoint.overlayOptions instanceof MarkerOptions) {
                    ((MarkerOptions) measurePoint.overlayOptions).position(measurePoint.selfPosition);
                }
                measurePoint.overlay = baiduMap.addOverlay(measurePoint.overlayOptions);
            }
        }
    }

    private void createMeasurLine() {
        MeasuringDistancePoint firstMeasurePoint = measuringDistancePoints.get(0);
        if (null == firstMeasurePoint || null == firstMeasurePoint.overlay || firstMeasurePoint.overlay.isRemoved())
            return;
        MeasuringDistancePoint secondMeasurePoint = measuringDistancePoints.get(1);
        if (null == secondMeasurePoint || null == secondMeasurePoint.overlay || secondMeasurePoint.overlay.isRemoved())
            return;
        List<LatLng> latLngs = new ArrayList<>();
        latLngs.add(firstMeasurePoint.selfPosition);
        latLngs.add(secondMeasurePoint.selfPosition);
        if (null == measuringDistanceLine) {
            measuringDistanceLine = new MeasuringDistanceLine();
            measuringDistanceLine.polylineOptions = new PolylineOptions()
                    .width(3)
                    .color(Color.parseColor("#ff99cc00"))
                    .points(latLngs)
                    .dottedLine(true);
            measuringDistanceLine.polyline = baiduMap.addOverlay(measuringDistanceLine.polylineOptions);

        } else {
            if (measuringDistanceLine.polyline instanceof Polyline) {
                if (measuringDistanceLine.polyline.isRemoved()) {
                    createLine(latLngs);
                }
            } else {
                createLine(latLngs);
            }
        }
        if (null != listener) {
            listener.onMeasuringDistanceListener(true, (int) DistanceUtil
                    .getDistance(firstMeasurePoint.selfPosition,secondMeasurePoint.selfPosition));
        }
    }

    private void createLine(List<LatLng> latLngs) {
        if (null == measuringDistanceLine.polylineOptions) {
            measuringDistanceLine.polylineOptions = new PolylineOptions()
                    .width(3)
                    .color(Color.parseColor("#ff99cc00"))
                    .points(latLngs)
                    .dottedLine(true);
        }
        measuringDistanceLine.polylineOptions.points(latLngs);
        measuringDistanceLine.polyline = baiduMap.addOverlay(measuringDistanceLine.polylineOptions);
    }

    private void clearMeasuringDistancePoint() {
        for (MeasuringDistancePoint distancePoint : measuringDistancePoints) {
            if (null != distancePoint.overlay) {
                if (!distancePoint.overlay.isRemoved()) {
                    distancePoint.overlay.remove();
                }
                distancePoint.overlay = null;
            }
        }
        if (null != measuringDistanceLine && null != measuringDistanceLine.polyline && !measuringDistanceLine.polyline.isRemoved()) {
            measuringDistanceLine.polyline.remove();
            measuringDistanceLine.polyline = null;
        }
        if (null != listener) {
            listener.onMeasuringDistanceListener(false,0);
        }
    }

    private boolean isHasMeasuringDistancePoint(int position) {
        if (measuringDistancePoints.size() <= position) return false;
        MeasuringDistancePoint distancePoint = measuringDistancePoints.get(position);
        if (null == distancePoint || null == distancePoint.overlay || distancePoint.overlay.isRemoved())
            return false;
        return true;
    }

    private void initData() {
        measuringDistancePoints = new ArrayList<>();
        for (String str : measureDistanceTexts) {
            createMeasuringDistancePoint(str);
        }
    }

    private void createMeasuringDistancePoint(String str) {
        MeasuringDistancePoint distancePoint = new MeasuringDistancePoint();
        distancePoint.text = str;
        distancePoint.bitmapDescriptor = measuringDistanceDrawble(distancePoint.text);
        Bundle params = new Bundle();
        if (distancePoint.text.equals("1")){
            params.putString(KEY_POINT,START_POINT);
        } else {
            params.putString(KEY_POINT,END_POINT);
        }
        distancePoint.overlayOptions = new MarkerOptions()
                .icon(distancePoint.bitmapDescriptor)
                .zIndex(priority)
                .extraInfo(params);
        measuringDistancePoints.add(distancePoint);
    }

    private BitmapDescriptor measuringDistanceDrawble(String text) {
        if (null == measuringDistancePoint) {
            measuringDistancePoint = LayoutInflater.from(activity).inflate(R.layout.measuring_distance_layout, null);
        }
        TextView tv = measuringDistancePoint.findViewById(R.id.tv);
        if (!TextUtils.isEmpty(text)) {
            tv.setText(text);
        }
        measuringDistancePoint.setDrawingCacheEnabled(true);
        measuringDistancePoint.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        measuringDistancePoint.layout(0, 0,
                measuringDistancePoint.getMeasuredWidth(),
                measuringDistancePoint.getMeasuredHeight());
        measuringDistancePoint.buildDrawingCache();
        //获取到图片，这样就可以添加到Map上
        return BitmapDescriptorFactory.fromView(measuringDistancePoint);
    }

    public void onDestroy() {
        if (null != mapClickListener && null != baiduMap) {
            baiduMap.setOnMapClickListener(null);
        }
        if (null != measuringDistanceLine) {
            if (null != measuringDistanceLine.polyline && !measuringDistanceLine.polyline.isRemoved()) {
                measuringDistanceLine.polyline.remove();
                measuringDistanceLine.polyline = null;
            }
            measuringDistanceLine.polylineOptions = null;
            measuringDistanceLine = null;
        }
        if (null != measuringDistancePoints) {
            for (MeasuringDistancePoint distancePoint : measuringDistancePoints) {
                distancePoint.recycle();
            }
            measuringDistancePoints.clear();
            measuringDistancePoints = null;
        }
        listener = null;
        measuringDistancePoint = null;
    }
}
